package com.duapk.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.duapk.web.Constants;
import com.duapk.web.log.LogManager;
import com.duapk.web.util.HttpUtils;
import static com.duapk.web.Constants.Home_Page;

public class VisitServlet extends HttpServlet {
	
	private static Logger logger = LoggerFactory.getLogger(VisitServlet.class);
	
	private static final long serialVersionUID = -7859507828549712238L;

	/**
	 * 注意中文问题:需要在server.xml 的 Connector 中增加 URIEncoding="gbk"
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String url = request.getParameter("u");
		if (url == null) {
			sendRedirect(response, Home_Page);
			return;
		}
		try {
			url = java.net.URLDecoder.decode(url, HttpUtils.UTF_HTTP_ENCODING);
			// url解密
			//url = EncryptorUtils.getDecryptionString(url);
		} catch (Exception e) {
			logger.error("Decode Url Error url={}",url,e);
			sendRedirect(response, Home_Page);
			return;
		}
		String name = request.getParameter("n");
		if (name == null) {
			sendRedirect(response, Home_Page);
			return;
		}
		try {
			name = java.net.URLDecoder
					.decode(name, HttpUtils.UTF_HTTP_ENCODING);
			//name = EncryptorUtils.getDecryptionString(name);
		} catch (Exception e) {
			logger.error("Decode name Error name={}",name,e);
			sendRedirect(response, Home_Page);
			return;
		}
		// 记录日志
		LogManager.visitLog(url,name, request.getRemoteHost(),
				request.getHeader(Constants.User_Agent));
		// 重定向
		sendRedirect(response, url);
	}

	/**
	 * 客户端重定向
	 * 
	 * @param request
	 * @param response
	 * @param url
	 * @throws ServletException
	 * @throws IOException
	 */
	private void sendRedirect(HttpServletResponse response, String url) throws ServletException,
			IOException {
		response.sendRedirect(url);
	}
}
